package com.bbc.commonbackstage.platform.utils;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson2.JSONObject;
import com.bbc.commonbackstage.common.constant.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * http工具类
 *
 * @author wl
 * @date 2022/12/19 16:23
 */
public class HttpUtils {

    /**
     * 发送post请求
     *
     * @param url 请求路径
     * @param params 请求参数
     * @author wl
     * @date 2022/12/19 16:27
     * @return java.lang.String
     */
    public static String sendPost(String url, JSONObject params) throws IOException {
        // 默认的请求头
        Map<String, String> headerMap = new HashMap<>(2);
        headerMap.put("Content-type", "application/json;charset=utf-8");
        headerMap.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        return sendPost(url, params, headerMap);
    }

    /**
     * 发送post请求
     *
     * @param url   请求地址
     * @param params 请求参数
     * @param headerMap 请求头参数
     * @author wl
     * @date 2022/12/13 10:35
     * @return java.lang.String
     */
    public static String sendPost(String url, JSONObject params, Map<String, String> headerMap) throws IOException {
        String body = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建POST方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 装填参数
        StringEntity s = new StringEntity(params.toString(), Constants.UTF8);
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.JSON.getValue()));
        // 设置参数到请求对象中
        httpPost.setEntity(s);
        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        // httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        headerMap.forEach(httpPost::setHeader);
        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        // 获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, Constants.UTF8);
        }
        EntityUtils.consume(entity);
        // 释放链接
        response.close();
        return body;
    }
}
